'use strict';

import {
  SmzdmRss
} from './SmzdmRss';
import {
  cache
} from "./CacheFile";
import X2JS from 'x2js';

let fs = require('fs');
let request = require('request');
let x2js = new X2JS();

class SmzdmRssPromise extends SmzdmRss {
  createCache(name, content) {
    let self = this;
    return new Promise((resolve, reject) => {
      cache.put(name, content, self._cacheTime, (key, value) => {
        self.fetchOne(name);
      });
      resolve({
        name,
        content
      });
    });
  }

  fetchOnline(rss) {
    let self = this;
    return new Promise((resolve, reject) => {
      let content = '';
      if (self._debug) {
        fs.readFile('./tests/feed.xml', 'utf-8', (error, body) => {
          if (error) {
            reject(error);
          } else {
            resolve(self.parseItems(body));
          }
        });
      } else {
        let url = self.getRssAttr(rss);
        console.log('[PromiseFetch]', 'Online');
        request(url, function (error, response, body) {
          if (error) {
            reject('服务器暂时无法请求');
          } else if (response && (response.statusCode !== 200)) {
            reject('无法获取服务端数据');
          } else {
            resolve(self.parseItems(body));
          }
        });
      }
    });
  }

  fetchOne(name, level = 'titles') {
    console.log('[Fetch One]', name);
    let self = this;
    return new Promise((resolve, reject) => {
      let content = cache.get(name);
      if (content) {
        resolve({
          name,
          content
        })
      } else {
        self.fetchOnline(name).then(result => {
          let content = {};
          if (result.length > 0) {
            switch (level) {
              case 'titles':
                let items = [];
                result.forEach((item, index) => {
                  items.push({
                    title: item.title
                  });
                });
                content = items;
                break;
              default:
                content = result;
                break;
            }
          }
          self.createCache(name, content);
          resolve({
            name,
            content
          })
        });
      }
    });
  }

  fetchAll(name, level = 'titles') {
    console.log('[Fetch All]', 'starting');
    let self = this;
    let promises = [];
    self._rss_sources.forEach((rss) => {
      if (name && name !== rss.name) {
        return
      }
      let promise = self.fetchOne(rss.name, level).then(result => {
        return new Promise((resolve, reject) => {
          resolve(result)
        });
      })
      promises.push(promise);
    });
    return Promise.all(promises).then(() => {
      console.log('[Fetch All]', 'done');
    });
  }
}

export default SmzdmRssPromise
export {
  SmzdmRssPromise
};
